<!--首页模块-->

<template>
  <!-- 主容器 -->
  <div class="home-container">
    <!-- TDesign 标题栏组件 -->
    <t-navbar 
      title="首页" 
      class="navbar"
      :left-arrow="false"
    >
    </t-navbar>
    
    <!-- 下拉刷新容器 -->
    <t-pull-down-refresh 
      v-model="refreshing" 
      @refresh="onRefresh"
      :loading-text="refreshing ? '正在刷新...' : '刷新完成'"
      :pull-down-distance="30"
      class="pull-refresh-container"
    >
      <t-list 
        :async-loading="loading" 
        @scroll="onScroll" 
        class="content-list"
      >
        <t-cell 
          v-for="item in listPull" 
          :key="item.id" 
          align="start" 
          class="list-item"
        >
          <div class="item-container">
            <!-- 头像 -->
            <t-avatar 
              class="avatar"
              :image="item.avatarUrl"
              :alt="`用户${item.id}的头像`"
              shape="circle"
              size="45px"
            />
            
            <!-- 文字内容和交互按钮容器 -->
            <div class="content-wrapper">
              <!-- 文字内容 -->
              <div class="cell-content">
                <div class="title-container">
                  <div class="content-title">用户 {{ item.id }}</div>
                  <div class="content-time">{{ formatRelativeTime(item.timestamp) }}</div>
                </div>
                <div class="content-text">这是列表项 {{ item.id }} 的详细内容</div>
              </div>
              
              <!-- 交互按钮组 -->
              <div class="action-buttons">
                <button 
                  class="action-btn" 
                  @click.stop="handleLike(item.id)"
                  :class="{ 'liked': likedItems.includes(item.id) }"
                >
                  <t-icon name="heart" :fill="likedItems.includes(item.id) ? '#ff4d4f' : 'none'" />
                  <span class="action-text">{{ item.likeCount }}</span>
                </button>
                
                <button class="action-btn" @click.stop="handleComment(item.id)">
                  <t-icon name="tips-double" />
                  <span class="action-text">{{ item.commentCount }}</span>
                </button>
                
                <button class="action-btn" @click.stop="handleMessage(item.id)">
                 <t-icon name="chat-bubble" />
                </button>
              </div>
            </div>
          </div>
        </t-cell>
        
        <!-- 加载状态提示 -->
        <template #loading>
          <div v-if="loading === 'loading'" class="loading-more">
            <t-loading size="16px">加载中...</t-loading>
          </div>
          <div v-else-if="listPull.length >= MAX_DATA_LEN" class="no-more">
            已经到底了
          </div>
        </template>
      </t-list>
    </t-pull-down-refresh>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { 
  Avatar as TAvatar, 
  Loading as TLoading, 
  Toast,
  Navbar as TNavbar,
  Icon as TIcon
} from 'tdesign-mobile-vue';

// 类型定义
interface ListItem {
  id: number;
  avatarUrl: string;
  timestamp: number;
  likeCount: number;
  commentCount: number;
}

// 常量定义
const MAX_DATA_LEN = 60;
const NAVBAR_HEIGHT = 48;
const ONCE_LOAD_NUM = 20;
const SCROLL_THRESHOLD = 50;

// 列表数据相关状态
const listPull = ref<ListItem[]>([]);
const loading = ref<string>('');
const refreshing = ref<boolean>(false);
const isLoading = ref<boolean>(false);
const hasMore = ref<boolean>(true);
const likedItems = ref<number[]>([]);

// 生成随机时间戳（过去7天内的随机时间）
const generateRandomTimestamp = (): number => {
  const now = Date.now();
  const sevenDaysAgo = now - 7 * 24 * 60 * 60 * 1000;
  return Math.floor(sevenDaysAgo + Math.random() * (now - sevenDaysAgo));
};

// 格式化相对时间
const formatRelativeTime = (timestamp: number): string => {
  const now = Date.now();
  const diffInSeconds = Math.floor((now - timestamp) / 1000);
  
  if (diffInSeconds < 60) {
    return `${diffInSeconds}秒前`;
  }
  
  const diffInMinutes = Math.floor(diffInSeconds / 60);
  if (diffInMinutes < 60) {
    return `${diffInMinutes}分钟前`;
  }
  
  const diffInHours = Math.floor(diffInMinutes / 60);
  if (diffInHours < 24) {
    return `${diffInHours}小时前`;
  }
  
  const diffInDays = Math.floor(diffInHours / 24);
  if (diffInDays < 7) {
    return `${diffInDays}天前`;
  }
  
  const date = new Date(timestamp);
  return `${date.getMonth() + 1}月${date.getDate()}日`;
};

// 生成随机互动数量
const generateRandomCount = (): number => {
  return Math.floor(Math.random() * 50);
};

// 模拟API加载数据
const fetchData = async (startId: number, count: number): Promise<ListItem[]> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      const temp: ListItem[] = [];
      for (let i = 0; i < count; i++) {
        const id = startId + i;
        temp.push({
          id,
          avatarUrl: `https://picsum.photos/seed/avatar${id}/200/200`,
          timestamp: generateRandomTimestamp(),
          likeCount: generateRandomCount(),
          commentCount: generateRandomCount()
        });
      }
      resolve(temp);
    }, 800);
  });
};

// 加载数据方法
const loadData = async (isRefresh: boolean = false): Promise<void> => {
  if (isLoading.value || (!isRefresh && !hasMore.value)) return;
  
  isLoading.value = true;
  
  try {
    const startId = isRefresh ? 1 : listPull.value.length + 1;
    const data = await fetchData(startId, ONCE_LOAD_NUM);
    
    if (isRefresh) {
      listPull.value = data;
      likedItems.value = [];
      hasMore.value = true;
    } else {
      listPull.value.push(...data);
    }
    
    if (listPull.value.length >= MAX_DATA_LEN) {
      hasMore.value = false;
    }
  } catch (error) {
    console.error('加载数据失败:', error);
    Toast.show({ content: '加载失败，请重试', theme: 'error' });
  } finally {
    isLoading.value = false;
    loading.value = '';
    refreshing.value = false;
  }
};

// 加载更多数据
const onLoadPull = async (): Promise<void> => {
  if (loading.value !== '') return;
  loading.value = 'loading';
  await loadData();
};

// 下拉刷新处理
const onRefresh = async (): Promise<void> => {
  if (refreshing.value) return;
  refreshing.value = true;
  await loadData(true);
};

// 滚动事件处理
const onScroll = (scrollBottom: number): void => {
  if (scrollBottom < SCROLL_THRESHOLD) {
    onLoadPull();
  }
};

// 点赞处理
const handleLike = (id: number): void => {
  const index = listPull.value.findIndex(item => item.id === id);
  if (index === -1) return;
  
  const likedIndex = likedItems.value.indexOf(id);
  if (likedIndex > -1) {
    likedItems.value.splice(likedIndex, 1);
    listPull.value[index].likeCount--;
    Toast.show({ content: '已取消点赞' });
  } else {
    likedItems.value.push(id);
    listPull.value[index].likeCount++;
    Toast.show({ content: '点赞成功' });
  }
};

// 评论处理
const handleComment = (id: number): void => {
  Toast.show({ content: `查看用户 ${id} 的评论` });
};

// 私信处理
const handleMessage = (id: number): void => {
  Toast.show({ content: `发送私信给用户 ${id}` });
};

// 组件挂载时加载初始数据
onMounted(() => {
  loadData();
});
</script>


<style scoped>
.home-container {
  min-height: 100vh;
  box-sizing: border-box;
  background-color: #f7f8fa;
}

.navbar {
  --td-navbar-height: v-bind('NAVBAR_HEIGHT + "px"');
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  z-index: 90;
}

.pull-refresh-container {
  padding-top: v-bind('NAVBAR_HEIGHT + "px"');
}

.content-list {
  height: 100%;
  background-color: #fff;
  margin: 0 1px;
  border-radius: 12px 12px 0 0;
  overflow: hidden;
}

.list-item {
  padding: 0;
}

.item-container {
  display: flex;
  align-items: flex-start;
  padding: 12px 16px;
  width: 100%;
  box-sizing: border-box;
  border-bottom: 1px solid #f5f5f5;
}

.avatar {
  flex-shrink: 0;
  margin-right: 12px;
  margin-top: 2px;
}

.content-wrapper {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
}

.cell-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
  margin-bottom: 8px;
}

.title-container {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  width: 100%;
  gap: 8px;
}

.content-title {
  font-weight: 500;
  color: #333;
  font-size: 16px;
  line-height: 1.4;
}

.content-time {
  color: #999;
  font-size: 12px;
  line-height: 1.4;
  margin-left: 8px;
  white-space: nowrap;
}

.content-text {
  text-align: left;
  color: #666;
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.4;
}

.action-buttons {
  display: flex;
  align-self: flex-end;
  gap: 16px;
  padding-top: 4px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  background: none;
  border: none;
  color: #999;
  font-size: 12px;
  cursor: pointer;
  padding: 4px 6px;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.action-btn:hover {
  background-color: #f5f5f5;
  color: #666;
}

.action-btn.liked {
  color: #ff4d4f;
}

.action-text {
  line-height: 1;
}

.loading-more,
.no-more {
  padding: 16px;
  text-align: center;
  color: #999;
  font-size: 14px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.no-more {
  color: #ccc;
  padding: 12px 0;
}
</style>